package com.ibl.rover.lite.client.Activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;

import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Utility.ReportDetail;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.CustomerBean;
import com.ibl.rover.lite.common.bean.OrderBean;
import com.ibl.rover.lite.common.bean.RouteBean;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class RouteOrdeReportActivity extends Activity {

	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;
	private List<OrderBean> orderList;
	private List<ReportDetail> reportDetailList;
	private Hashtable<String, Double> datalist;
	private Hashtable<String, String> routelist;
	private Hashtable<String, String> productivelist;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.route_order_report);
		initialize();
	}

	private void initialize() {
		try {
			roverApp = (ApplicationContext) getApplication();
			manager = roverApp.getDatabaseManager();
			routelist = new Hashtable<String, String>();
			reportDetailList = new ArrayList<ReportDetail>();
			getRoute();
			buildRouteOrderTable();
		} catch (Exception e) {
			logger.logException("Intialization error", e);
		}
	}

	private void getorderRoutWise() {
		try {

		} catch (Exception e) {
			logger.logException("getorderRoutWise ", e);
		}

	}

	/**
	 * 
	 * @return Route Values
	 */
	private String[] getRouteInfo() {
		String[] routeNumber = null;
		Cursor cursor = null;
		try {
			cursor = manager.executeDistinctSQL(RouteBean.class,
					new String[] { RouteBean.COL_CODE });

			cursor.moveToFirst();
			routeNumber = new String[cursor.getCount()];
			int i = 0;
			while (!cursor.isAfterLast()) {
				routeNumber[i++] = cursor.getString(0).trim();
				cursor.moveToNext();
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.logException("getRouteInfo Exception", e);
		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return routeNumber;

	}

	private void getRoute() {
		try {
			datalist = new Hashtable<String, Double>();
			String[] routeInfo = getRouteInfo();
			ReportDetail reportDetail;
			double orderAMount;
			for (String routeCode : routeInfo) {
				reportDetail = new ReportDetail();
				orderAMount = getOrders(routeCode, reportDetail);
				if (orderAMount > 0)
					datalist.put(routeCode, orderAMount);
			}

		} catch (Exception e) {
			logger.logException("getOrders Exception", e);
		}

	}

	private double getOrders(String routeCode, ReportDetail reportDetail) {
		double amount = 0;
		try {

			Criteria<CustomerBean> customerCriteria = manager
					.generateCriteria(CustomerBean.class);

			customerCriteria.addRestriction(CustomerBean.COL_ROUTE_NUMBER,
					Operators.isEqual, routeCode);

			List<CustomerBean> customerList = customerCriteria.execute();

			Criteria<OrderBean> orderCriteria = manager
					.generateCriteria(OrderBean.class);
			orderCriteria.addRestrictionWithAnd(OrderBean.COL_STATUS,
					Operators.isEqual, "Active");
			CustomerBean customerBean ;
			customerBean=customerList.get(0);
				orderCriteria.startCriteriaWithAnd(OrderBean.COL_CUSTOMER_CODE,
						Operators.isEqual, customerBean.getCode());
		
			for (int i=1;i< customerList.size();i++) {
				customerBean=null;
				customerBean=customerList.get(i);
				orderCriteria.addRestriction(OrderBean.COL_CUSTOMER_CODE,
						Operators.isEqual, customerBean.getCode());
			}
orderCriteria.endCriteria();
			reportDetail.setRouteCode(routeCode);
			reportDetail.setRoutedCustomerCount(String.valueOf(customerList
					.size()));
			// routelist.put(routeCode, String.valueOf(customerList.size()));
			
			orderList = orderCriteria.execute();
			double orderAmount = 0;
			for (OrderBean orderBean : orderList) {
				orderAmount = Double.valueOf(orderBean.getAmount());
				amount += orderAmount;

			}
			reportDetail.setRoutedProductiveCustomerCount(String
					.valueOf(orderList.size()));
			if (amount > 0) {
				reportDetail.setRouteOrderAmount(amount);
				reportDetailList.add(reportDetail);
			}

			// productivelist.put(routeCode, String.valueOf(orderList.size()));
		} catch (Exception e) {
			logger.logException("getOrders Exception", e);
		}
		return amount;
	}

	private void buildRouteOrderTable() {
		try {
			TableLayout retailersTablereouteCustromerTable = (TableLayout) findViewById(R.id.report_order_table);
			int textColor = getResources().getColor(
					R.color.table_item_text_color);
			if (retailersTablereouteCustromerTable.getChildCount() > 1) {
				retailersTablereouteCustromerTable.removeViews(1,
						retailersTablereouteCustromerTable.getChildCount() - 1);
			}
			LayoutParams otherParams = new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

			otherParams.setMargins(1, 0, 0, 1);
			String date = returnOrderCurrentDate();

			TextView total = ((TextView) findViewById(R.id.lbl_total_amount));
			double totalAmount = 0;
			for (ReportDetail reportDetail : reportDetailList) {
				TableRow row = new TableRow(this);
				row.setTag(reportDetail);
				totalAmount += reportDetail.getRouteOrderAmount();
				TextView txtCustomerShopname = new TextView(this);
				txtCustomerShopname.setTextAppearance(this,
						R.style.table_item_font);
				txtCustomerShopname.setText(date);
				txtCustomerShopname.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtCustomerShopname.setPadding(5, 0, 5, 0);
				txtCustomerShopname.setTextColor(textColor);

				row.addView(txtCustomerShopname, otherParams);

				TextView txtRouteCode = new TextView(this);
				txtRouteCode.setTextAppearance(this, R.style.table_item_font);
				txtRouteCode.setText(reportDetail.getRouteCode());
				txtRouteCode.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtRouteCode.setPadding(5, 0, 5, 0);
				txtRouteCode.setTextColor(textColor);

				row.addView(txtRouteCode, otherParams);

				TextView txtCalls = new TextView(this);
				txtCalls.setTextAppearance(this, R.style.table_item_font);
				txtCalls.setText(reportDetail.getRoutedCustomerCount());
				txtCalls.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtCalls.setPadding(5, 0, 5, 0);
				txtCalls.setTextColor(textColor);

				row.addView(txtCalls, otherParams);

				TextView txtProductiveCalls = new TextView(this);
				txtProductiveCalls.setTextAppearance(this,
						R.style.table_item_font);
				txtProductiveCalls.setText(reportDetail
						.getRoutedProductiveCustomerCount());
				txtProductiveCalls.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtProductiveCalls.setPadding(5, 0, 5, 0);
				txtProductiveCalls.setTextColor(textColor);

				row.addView(txtProductiveCalls, otherParams);

				TextView txtAmount = new TextView(this);
				txtAmount.setTextAppearance(this, R.style.table_item_font);
				txtAmount.setText(String.valueOf(reportDetail
						.getRouteOrderAmount()));
				txtAmount.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtAmount.setPadding(5, 0, 5, 0);
				txtAmount.setTextColor(textColor);

				row.addView(txtAmount, otherParams);

				retailersTablereouteCustromerTable.addView(row);
				retailersTablereouteCustromerTable.invalidate();
			}

			total.setText("Total :" + String.valueOf(totalAmount));

		} catch (Exception e) {
			logger.logException("Search Cusetomer", e);
		}

	}

	private String returnOrderCurrentDate() {
		try {

			Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
			String day = c.get(Calendar.DAY_OF_MONTH) >= 10 ? Integer
					.toString(c.get(Calendar.DAY_OF_MONTH)) : "0"
					+ Integer.toString(c.get(Calendar.DAY_OF_MONTH));
			String month = c.get(Calendar.MONTH) >= 10 ? Integer.toString(c
					.get(Calendar.MONTH) + 1) : "0"
					+ Integer.toString(c.get(Calendar.MONTH) + 1);
			String year = Integer.toString(c.get(Calendar.YEAR));
			String currentdate = day + "-" + month + "-" + year;

			c = null;
			day = null;
			month = null;
			year = null;

			return currentdate;
		} catch (Exception e) {
			logger.logException("returnOrderCurrentDate Exception", e);
		}
		return null;
	}

}
